package com.aifast.system.sys.service;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.aifast.common.base.R;
import com.aifast.common.layui.LayuiDataTable;
import com.aifast.common.layui.LayuiPageFactory;
import com.aifast.system.sys.dao.SysAuthoritiesDao;
import com.aifast.system.sys.dao.SysRoleAuthorityDao;
import com.aifast.system.sys.dao.SysRoleDao;
import com.aifast.system.sys.dao.SysUserRoleDao;
import com.aifast.system.sys.entity.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author fujian
 * @since 2021-12-30
 */
@Service
public class SysRoleService extends ServiceImpl<SysRoleDao, SysRole> {

    @Autowired
    private SysRoleDao sysRoleDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;
    @Autowired
    private SysRoleAuthorityDao sysRoleAuthorityDao;
    @Autowired
    private SysAuthoritiesDao sysAuthoritiesDao;

    public LayuiDataTable list(String search, Integer permissionType, Page page) {
        LambdaQueryWrapper<SysRole> wrapper = sysRoleDao.list(search,permissionType);
        LayuiDataTable<SysRole> init = LayuiPageFactory.init(page(page, wrapper));
        return init;
    }

    public Boolean insertOrUpdate(SysRole sysRole){
        if(ObjectUtil.isNotNull(sysRole.getId())){
            UserInfo.removeByRole(sysRole.getId());
        }
        return saveOrUpdate(sysRole);
    }

    public Boolean del(Integer id, String ids) {
        List<Integer> integers = new ArrayList<>();
        if (StrUtil.isNotBlank(ids)) {
            integers = Convert.toList(Integer.class, ids.split(","));
        }
        if (!Objects.equals(null, id)) {
            integers.add(id);
        }
        try {
            integers.forEach(i -> {
                update(new UpdateWrapper<SysRole>().set("deleted", 1).eq("id",i));
                UserInfo.removeByRole(i);
            });
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    public R info(Integer id) {
        if(ObjectUtil.isNull(id)){
            return R.ERROR();
        }
        SysRole one = getOne(new QueryWrapper<SysRole>().eq("id", id).last("limit 1"));
        return R.OK(one);
    }

    public R info1(Integer id) {
        if(ObjectUtil.isNull(id)){
            return R.ERROR();
        }
        Map<String, Object> one = getMap(new QueryWrapper<SysRole>().eq("id", id).last("limit 1"));
        return R.OK(one);
    }

    /**
     * 获取用户的所有角色集合
     * @param userId 用户id
     * @return
     */
    public List<SysRole> getRoles(Integer userId) {

        List<SysUserRole> userRoles = sysUserRoleDao.selectList(new QueryWrapper<SysUserRole>().eq("user_id", userId));
        if(userRoles.size() == 0){
            return ListUtil.empty();
        }
        List<SysRole> roles = sysRoleDao.selectList(new QueryWrapper<SysRole>().in("id", userRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList())).orderByDesc("priority"));
        return roles;
    }

    /**
     * 获取用户的所有角色的权限集合
     * @param userId 用户id
     * @return
     */
    public List<String> getAuthorities(Integer userId) {
        List<SysRole> roles = getRoles(userId);
        List<String> empty = ListUtil.empty();
        if(roles.size() == 0 ){ return empty; }
        List<SysRoleAuthority> roleAuthorities = sysRoleAuthorityDao.selectList(new QueryWrapper<SysRoleAuthority>().in("role_id", roles.stream().map(SysRole::getId).collect(Collectors.toList())));
        if(roleAuthorities.size() == 0){return empty;}
        List<SysAuthorities> authorities = sysAuthoritiesDao.selectList(new QueryWrapper<SysAuthorities>().in("id", roleAuthorities.stream().map(SysRoleAuthority::getAuthorityId).collect(Collectors.toList())));
        if(authorities.size() == 0){return empty;}

        return authorities.stream().map(SysAuthorities::getAuthority).filter(i->StrUtil.isNotBlank(i)).collect(Collectors.toList());
    }
}
